package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.DivideConquer;

import java.util.Arrays;

/**
 * 这个写法应该或许可能是logn吧
 *
 * @author tzp
 * @since 2020/10/20
 */
public class LC33_1 implements DivideConquer {

    public int search(int[] nums, int target) {
        return rec(nums, target, 0, nums.length);
    }

    public int rec(int[] nums, int target, int start, int end) {
        if (start == end) return nums[start] == target ? start : -1;
        if (nums[start] <= nums[end - 1]) {//本段没旋转
            int i = Arrays.binarySearch(nums, start, end, target);
            return i < 0 ? -1 : i;
        } else {
            int mid = start + (end - start - 1) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {//往左
                int i = rec(nums, target, start, mid);
                if (i < 0 && nums[end - 1] >= target) {
                    i = rec(nums, target, mid + 1, end);
                }
                return i;
            } else if (nums[mid] < target) {
                int i = rec(nums, target, mid + 1, end);
                if (i < 0 && nums[start] <= target) {
                    i = rec(nums, target, start, mid);
                }
                return i;
            } else {
                return -100;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new LC33_1().search(new int[]{4, 5, 6, 7, 8, 1, 2, 3}, 8));
        System.out.println(new LC33_1().search(new int[]{3, 4, 5, 6, 1, 2}, 2));
        System.out.println(new LC33_1().search(new int[]{1}, 6));
        System.out.println(new LC33_1().search(new int[]{3, 1}, 6));
        System.out.println(new LC33_1().search(new int[]{4, 5, 6, 7, 8, 9, 10, 11, 3}, 3));
        for (int i = 0; i < 9; i++) {
            System.out.println(new LC33_1().search(new int[]{4, 5, 6, 7, 0, 1, 2}, i));
        }
    }
}
